package com.h3c.nem.async;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eos.common.util.IdWorker;
import com.h3c.nem.entity.*;
import com.h3c.nem.mapper.SdUserMapper;
import com.h3c.nem.mapper.TbOfferWorkerMapper;
import com.h3c.nem.service.CommService;
import com.h3c.nem.service.ISdDeptService;
import com.h3c.nem.service.ISdTodoTaskService;
import com.h3c.nem.service.ThreadPoolService;
import com.h3c.nem.utils.BusiEnumDefine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Component
public class AsyncSendMessage {

    @Value("${system.url}")
    private String systemUrl;
    @Autowired
    CommService commService;
    @Resource
    private SdUserMapper sdUserMapper;
    @Resource
    private ISdDeptService sdDeptService;
    @Resource
    private TbOfferWorkerMapper offerWorkerMapper;
    @Resource
    private ThreadPoolService threadPoolService;
    @Autowired
    ISdTodoTaskService todoTaskService;

    public void sendMessage(List<SdNoticeRecord> message) {
        Thread thread = new Thread(() -> {
            commService.sendMessage(message);
        });
        threadPoolService.submitTask(thread);
    }

    public void sendMessage(SdNoticeRecord message, List<File> fileList) {
        Thread thread = new Thread(() -> {
            commService.sendMessage(message, fileList);
        });
        threadPoolService.submitTask(thread);
    }

    public void sendMessage(SdNoticeRecord message, List<File> fileList, List<String> accountList) {
        Thread thread = new Thread(() -> {
            commService.sendMessage(message, fileList, accountList);
        });
        threadPoolService.submitTask(thread);
    }

    public void sendTodoTask(Iterable<SdTodoTask> tasks) {
        Thread thread = new Thread(() -> {
            tasks.forEach(i -> {
                todoTaskService.save(i);
                todoTaskService.sendTodoTask(i);
            });
        });
        threadPoolService.submitTask(thread);
    }

    public void onlySendTodoTask(Iterable<SdTodoTask> tasks, Boolean updateFlag) {
        Thread thread = new Thread(() -> {
            tasks.forEach(i -> {
                if (updateFlag) {
                    todoTaskService.updateTodoTask(i);
                }
                todoTaskService.sendTodoTask(i);
            });
        });
        threadPoolService.submitTask(thread);
    }

    public void sendMailToRelated(List<String> preWorkerIds) {
        Thread thread = new Thread(() -> {
            log.info("发送邮件给入职期BP和接口人");
            if (CollectionUtils.isEmpty(preWorkerIds)) {
                return;
            }
            SimpleDateFormat sdf = new SimpleDateFormat("y-M-d");
            Date createTime = new Date();
            List<TbOfferWorker> tbOfferWorkers = offerWorkerMapper.selectBatchIds(preWorkerIds);
            List<SdUser> bpUser = sdUserMapper.selectList(new QueryWrapper<>());
            List<String> offerBpList = new ArrayList<>();
            List<String> bpList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(bpUser)) {
                bpUser.forEach(bp -> {
                    for (String role : bp.getUserRole().split(",")) {
                        if (Integer.valueOf(role) == BusiEnumDefine.USER_ROLE_OFFER_BP){
                            offerBpList.add(bp.getUserId());
                        }
                        if (Integer.valueOf(role) == BusiEnumDefine.USER_ROLE_NEW_WORKER_BP){
                            bpList.add(bp.getUserId());
                        }
                    }
                });
            }
            Map<String, StringBuilder> mailContentMap = new HashMap<>();
            tbOfferWorkers.forEach(worker -> {
                String bpIds = sdDeptService.getBpByDeptNameChain(worker.getDeptNameChain(), offerBpList, bpList);
                String contactor = sdDeptService.getContactorByDeptNameChain(worker.getDeptNameChain(), worker.getWorkCity());
                SdDept dept = sdDeptService.getDeptByNameChainNoException(worker.getDeptNameChain());
                if (StringUtils.hasText(bpIds + contactor)) {
                    for (String id : (bpIds + contactor).split(",")) {
                        if (StringUtils.hasText(id)) {
                            StringBuilder mailSb = new StringBuilder();
                            StringBuilder builder = mailContentMap.get(id);
                            if (builder == null) {
                                mailSb.append("您好！您负责的部门有以下待入职员工的预备工号已生成，请进入系统检视，相关信息如有变化请及时在预备员工管理页面下编辑更改。<br>");
                                mailContentMap.put(id, mailSb);
                            } else {
                                mailSb = builder;
                            }
                            mailSb.append(worker.getWorkerName()).append("/").append(worker.getWorkerId()).append(" ");
                            if (worker.getPlanReportDate() != null) {
                                mailSb.append("预计报到日期：").append(sdf.format(worker.getPlanReportDate())).append(" ");
                            }
                            if (StringUtils.hasText(worker.getDeptNameChain())) {
                                mailSb.append("计划入职部门：").append(worker.getDeptNameChain()).append(" ");
                            }
                            if (dept != null) {
                                if ("RD".equals(dept.getDeptType())) {
                                    mailSb.append("班次：班次A-08:30-18:00 ")
                                            .append("考勤类型：手工考勤 ")
                                            .append("员工类型：研发 ")
                                            .append("办公区域：研发区 ");
                                } else {
                                    mailSb.append("班次：班次C-08:30-17:30 ")
                                            .append("考勤类型：手工考勤 ")
                                            .append("员工类型：非研发 ")
                                            .append("办公区域：非研发区 ");
                                }
                            }
                            mailSb.append("<br>");
                        }
                    }
                }
            });
            log.info("组装邮件map={}", mailContentMap);
            mailContentMap.forEach((k, v) -> {
                SdAllWorker workerDO = commService.getAllWorkerDoFromLocalCache(k);
                if (workerDO != null) {
                    v.append("<br>").append("链接地址：").append(systemUrl);
                    SdNoticeRecord noticeRecord = new SdNoticeRecord();
                    noticeRecord.setNoticeId(IdWorker.nextId() + "");
                    noticeRecord.setFlowId("-1");
                    noticeRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
                    noticeRecord.setTargetId(workerDO.getWorkerId());
                    noticeRecord.setTargetName(workerDO.getWorkerName());
                    noticeRecord.setTargetEmail(workerDO.getEmail());
                    noticeRecord.setNoticeTitle("待入职员工预备工号已生成");
                    noticeRecord.setNoticeContent(v.toString());
                    noticeRecord.setCreateTime(createTime);
                    commService.sendMessage(noticeRecord);
                }
            });
        });
        threadPoolService.submitTask(thread);
    }
}
